
package net.blogways.ordermgr.mail.util;

import net.blogways.ordermgr.mail.entity.Mail;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.retry.annotation.Retryable;

public class MailUtils {

  protected static Logger logger = LoggerFactory.getLogger(MailUtils.class);

  @Retryable(value = {EmailException.class},maxAttempts = 3)
  public static boolean sendMail(Mail mail) throws EmailException {
    //发送email对象
    HtmlEmail email = new HtmlEmail();
    //这里是SMTP发送服务器的名字
    email.setHostName(mail.getHost());
    //端口号不为空时,用户自定义的端口号为SMTP发送服务器端口号
    logger.debug("email Host--------" + mail.getHost());
    if (!"".equals(mail.getPortNumber())) {
      email.setSSLOnConnect(true);
      email.setSslSmtpPort(mail.getPortNumber());
    }
    //字符编码集的设置
    email.setCharset(Mail.ENCODEING);
    logger.debug("email encodeing---" + Mail.ENCODEING);
    //收件人的邮箱
    email.addTo(mail.getReceiver());
    logger.debug("mail收件人邮箱----" + mail.getReceiver());
    //发送人的邮箱
    email.setFrom(mail.getSender(), mail.getName());
    logger.debug("发件人的邮箱------" + mail.getSender());
    logger.debug("用户名------" + mail.getName());
    // 如果需要认证信息的话，设置认证：用户名-密码。分别为发件人在邮件服务器上的注册名称和密码
    email.setAuthentication(mail.getUsercode(), mail.getPassword());
    // 要发送的邮件主题
    email.setSubject(mail.getSubject());
    logger.debug("主题--------------" + email.getSubject());
    // 要发送的信息，由于使用了HtmlEmail，可以在邮件内容中使用HTML标签
    email.setMsg(mail.getMessage());
    logger.debug("信息内容----------" + mail.getMessage());
    if (mail.getAttachment() != null) {
      email.attach(mail.getAttachment());
    }
    String copySomeone = mail.getCopySomeone();
    if(copySomeone != null && !"".equals(copySomeone)){
      String[] collection = copySomeone.split(";");
      logger.debug("collection:" + collection);
      email.addCc(collection);
    }
    System.out.println("mail" + mail);
    // 发送
    email.send();
    return true;
  }

}
